package com.xzer.xiaozhuoerinterface.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xzer.xiaozhuoerinterface.entity.*;
import com.xzer.xiaozhuoerinterface.mapper.InfoMapper;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;

/**
 * @program: Xiaozhuoer-interface
 * @description:
 * @author: Xiaozhuoer
 * @create: 2021-09-13 15:20
 **/

@Service
public class HelloService {
    private final InfoMapper infoMapper;

    public HelloService(InfoMapper infoMapper) {
        this.infoMapper = infoMapper;
    }

    public HttpResult Hello(){
        HttpResult httpResult = new HttpResult();
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("Hello");
        return httpResult;
    }

    public HttpResult UpLoad(PerInfo perInfo){
        HttpResult httpResult = new HttpResult();
        double creditRate = CalCreditRate(perInfo);
        perInfo.setCreditRate(String.valueOf(creditRate));
        infoMapper.UpLoadInfo(perInfo);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("UpLoad");
        return httpResult;
    }

    public HttpResult reg(LoginInfo loginInfo) {
        HttpResult httpResult = new HttpResult();
        if(infoMapper.reg(loginInfo) >= 0){
            httpResult.setData(loginInfo.getId());
            httpResult.setStatus(0);
            httpResult.setMsg("success");
        }else{
            httpResult.setData("");
            httpResult.setStatus(1);
            httpResult.setMsg("fail");
        }
        return httpResult;
    }

    public HttpResult login(LoginInfo loginInfo) {
        HttpResult httpResult = new HttpResult();
        loginInfo = infoMapper.login(loginInfo);
        if(loginInfo.getId() >= 0){
            try {
                Idcardtable idcardtable = infoMapper.getIdCardTable(loginInfo.getUsername());
                loginInfo.setIdcardtable(idcardtable);
                infoMapper.getIdCardTable(loginInfo.getUsername());
                DriverTable driverTable = infoMapper.getDriverTable(loginInfo.getIdcardtable().getFullname());
                loginInfo.setDriverTable(driverTable);
                List<BankCardTable> bankCardTableList = infoMapper.getBankCardTable(loginInfo.getIdcardtable().getIdcardnum());
                loginInfo.setBankCardTableArrayList(bankCardTableList);
                List<CarTable> carTableList = infoMapper.getCarTable(loginInfo.getIdcardtable().getFullname());
                loginInfo.setCarTableArrayList(carTableList);
                loginInfo.setBankCredit(BankCreditSum(loginInfo.getIdcardtable().getIdcardnum()));
            }catch (Exception e){
                System.out.println(e);
            }finally {
                httpResult.setData(loginInfo);
                httpResult.setStatus(0);
                httpResult.setMsg("success");
            }
        }else{
            httpResult.setData("");
            httpResult.setStatus(1);
            httpResult.setMsg("fail");
        }
        return httpResult;
    }

    public HttpResult getCredit(String idCardNum) {
        HttpResult httpResult = new HttpResult();
        String creditRate = infoMapper.getCreditRate(idCardNum);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(creditRate);
        return httpResult;
    }

    public HttpResult shareBike(String username,String platType) {
        HttpResult httpResult = new HttpResult();
        PlatInfo platInfo = infoMapper.getShareBikeLimit(platType);
        int iShareBikeLimit = platInfo.getLimit();
        int iNameCredit = infoMapper.getCreditRateByUsername(username);
        if(iNameCredit >= iShareBikeLimit )
        {
            httpResult.setStatus(0);
            httpResult.setMsg("success");
            httpResult.setData("");
            return httpResult;
        }
        httpResult.setStatus(-1);
        httpResult.setMsg("credit is low");
        httpResult.setData("");
        return httpResult;
    }

    public HttpResult shareCar(String username,String carType) {
        HttpResult httpResult = new HttpResult();
        Integer ret = infoMapper.getDriverCardByUsername(username);
        if(ret != null)
        {
            PlatInfo platInfo = infoMapper.getShareCarLimit(carType);
            int iNameCredit = infoMapper.getCreditRateByUsername(username);
            if(iNameCredit >= platInfo.getLimit() )
            {
                httpResult.setStatus(0);
                httpResult.setMsg("success");
                httpResult.setData("");
                return httpResult;
            }
            httpResult.setStatus(-1);
            httpResult.setMsg("credit is low");
            httpResult.setData("");
            return httpResult;
        }
        httpResult.setStatus(-2);
        httpResult.setMsg("no drivercard");
        httpResult.setData("");
        return httpResult;
    }

    public int getIdCardTableId(String username) {
        int id = infoMapper.getIdCardTableInfo(username);
        if(id > 0) {
            return id;
        }
        return -1;
    }

    public HttpResult InsertIdCardTable(Idcardtable idcardtable) {
        HttpResult httpResult = new HttpResult();
        if(infoMapper.insertIdCardTable(idcardtable) >= 0){
            Credit credit = new Credit(idcardtable.getFullname(), idcardtable.getIdcardnum(), 10);
            infoMapper.insertCredit(credit);
            infoMapper.updateLoginFullnameAndCredit(idcardtable.getName(),idcardtable.getFullname(), credit.getCreditrate());
            infoMapper.updateLoginCredit(idcardtable.getFullname(), credit.getCreditrate());
            httpResult.setData(credit.getCreditrate());
            httpResult.setStatus(0);
            httpResult.setMsg("success");
        }else{
            httpResult.setData("");
            httpResult.setStatus(-1);
            httpResult.setMsg("fail");
        }
        return httpResult;
    }

    public HttpResult uploadDriverData(DriverTable driverTable) {
        HttpResult httpResult = new HttpResult();
        Integer ret = infoMapper.getDriverTableId(driverTable.getName());
        if(ret != null)
        {
            infoMapper.updateDriverTable(driverTable);
            httpResult.setData("");
            httpResult.setStatus(0);
            httpResult.setMsg("success");
        }else {
            if(infoMapper.insertDriverTable(driverTable) >= 0){
                infoMapper.updateDriverTable(driverTable);
                int iCreditRate = infoMapper.getCreditRateByUsername(driverTable.getName());
                infoMapper.updateCreditRate(driverTable.getName(), iCreditRate + 10);
                infoMapper.updateLoginCredit(driverTable.getName(),iCreditRate + 10);
                httpResult.setData(iCreditRate+10);
                httpResult.setStatus(0);
                httpResult.setMsg("success");
            }else{
                httpResult.setData("");
                httpResult.setStatus(-1);
                httpResult.setMsg("fail");
            }
        }
        return httpResult;
    }

    public HttpResult cleanDriverData(String name,String credit) {
        HttpResult httpResult = new HttpResult();
        infoMapper.deleteDriverTable(name);
        infoMapper.updateCreditRate(name, Integer.parseInt(credit) - 10);
        infoMapper.updateLoginCredit(name, Integer.parseInt(credit) - 10);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("");
        return httpResult;
    }

    public HttpResult selCleanCarData(String strNum) {
        HttpResult httpResult = new HttpResult();
        String[] strNumArr = strNum.split("\\|");
        for (String s : strNumArr) {
            infoMapper.deleteCarTable(s);
        }
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(strNum);
        return httpResult;
    }

    public HttpResult cleanCarData(String fullname, String credit) {
        HttpResult httpResult = new HttpResult();
        infoMapper.deleteAllCarTable(fullname);
        infoMapper.updateCreditRate(fullname, Integer.parseInt(credit) + 10);
        infoMapper.updateLoginCredit(fullname, Integer.parseInt(credit) + 10);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("");
        return httpResult;
    }

    public HttpResult uploadCarData(String carTableJson, String carowner, String credit) {
        HttpResult httpResult = new HttpResult();
        // Json转JsonArray 批量处理
        JSONArray jsonArray = JSONArray.parseArray(carTableJson);
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(o.toString());
            CarTable carTable = jsonObject.toJavaObject(CarTable.class);
            if (infoMapper.insertCarTable(carTable) < 0) {
                httpResult.setStatus(-1);
                httpResult.setMsg("fail");
                httpResult.setData("");
                return httpResult;
            }
        }
        infoMapper.updateCreditRate(carowner, Integer.parseInt(credit) + 10);
        infoMapper.updateLoginCredit(carowner, Integer.parseInt(credit) + 10);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("");
        return httpResult;
    }

    public HttpResult uploadBankCardData(String bankCardTableJson, String name ,String credit) {
        HttpResult httpResult = new HttpResult();
        // Json转JsonArray 批量处理
        JSONArray jsonArray = JSONArray.parseArray(bankCardTableJson);
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(o.toString());
            BankCardTable bankCardTable = jsonObject.toJavaObject(BankCardTable.class);
            if (infoMapper.insertBankCardTable(bankCardTable) < 0) {
                httpResult.setStatus(-1);
                httpResult.setMsg("fail");
                httpResult.setData("");
                return httpResult;
            }
        }
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("");
        return httpResult;
        //TODO 数据上传成功了，接下来的删除数据
    }

    public HttpResult selCleanBankCardData(String strNum) {
        HttpResult httpResult = new HttpResult();
        String[] strNumArr = strNum.split("\\|");
        for (String s : strNumArr) {
            infoMapper.deleteBankCardTable(s);
        }
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(strNum);
        return httpResult;
    }

    public double CalCreditRate(PerInfo perInfo){
//        身份证信息是否齐全		齐全50 不齐全20
//	         （年龄）18岁-30岁 10——50
//        银行卡			信用卡0.5，储蓄卡1
//        驾驶证信息是否齐全 		齐全1 不齐全0.5
//        行驶证信息是否齐全 		齐全0.5 不齐全0.2
//	    （车的使用时间）	5年 0.1——0.5
        double creditRate = 0;
        //身份证
        double idCardRate = 100;
        if(perInfo.getName() == "") {
            idCardRate = idCardRate - 10;
        }
        if(perInfo.getSex() == "") {
            idCardRate = idCardRate - 10;
        }
        if(perInfo.getNation() == "") {
            idCardRate = idCardRate - 10;
        }
        if(perInfo.getBirth() == "") {
            idCardRate = idCardRate - 10;
        }else{
            int year = Integer.parseInt(perInfo.getBirth().substring(0,4));
            Calendar c = Calendar.getInstance();
            int nowYear = c.get(Calendar.YEAR);
            int age = nowYear - year;
            //未成年人
            if(age < 18){
                idCardRate = 0;
                return idCardRate;
            }else if(age > 17 && age <30){
                int temp = 50-(((12-(30-age))/12)*50);
                idCardRate = idCardRate - temp;
            }
        }
        if(perInfo.getIdCardNum() == "") {
            idCardRate = 0;
            return idCardRate;
        }
        //银行卡
        double bankCardRate = 100;
        if(perInfo.getBankName() == ""){
            bankCardRate = bankCardRate - 20;
        }
        if(perInfo.getBankCardType() == ""){
            bankCardRate = bankCardRate - 20;
        }else{
            //借记卡-> 储蓄卡    贷记卡->信用卡
            if(perInfo.getBankCardType() == "贷记卡"){
                bankCardRate = bankCardRate - 30;
            }
        }
        if(perInfo.getBankCardNum() == ""){
            bankCardRate = 0;
        }
        //行驶证
        double carRate = 100;
        if(perInfo.getCarId() == ""){
            carRate = carRate - 10;
        }
        if(perInfo.getLicenseData() == ""){
            carRate = carRate - 10;
        }else{
            int year = Integer.parseInt(perInfo.getLicenseData().substring(0,4));
            Calendar c = Calendar.getInstance();
            int nowYear = c.get(Calendar.YEAR);
            int carAge = nowYear - year;
            if(carAge < 5){
                int temp = 50-((carAge/5)*50);
                carRate = carRate - temp;
            }
        }
        if(perInfo.getCarModel() == ""){
            carRate = carRate - 10;
        }
        if(perInfo.getCarOwner() == ""){
            carRate = carRate - 10;
        }
        if(perInfo.getLicenseData() == ""){
            carRate = carRate - 10;
        }
        //驾驶证
        double driverRate = 100;
        if(perInfo.getDriverLastData() == ""){
            driverRate = driverRate - 50;
        }
        if(perInfo.getDriverCardNum() == ""){
            driverRate = driverRate - 50;
        }
        creditRate = (idCardRate + bankCardRate + carRate + driverRate)/400;
        return creditRate;
    }

    public HttpResult getAllInfo() {
        HttpResult httpResult = new HttpResult();
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(infoMapper.getAllInfo());
        return httpResult;
    }

    public HttpResult deleteInfoFromId(String idCardNum) {
        HttpResult httpResult = new HttpResult();
        infoMapper.deleteInfoFromId(idCardNum);
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData("");
        return httpResult;
    }

    public HttpResult getCarData(String fullname) {
        List<CarTable> carTableList = infoMapper.getCarTable(fullname);
        String strJson = JSON.toJSONString(carTableList);
        HttpResult httpResult = new HttpResult();
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(JSONObject.parse(strJson));
        return httpResult;
    }

    public HttpResult getBankCardData(String idcardnum) {
        List<BankCardTable> bankCardTableList = infoMapper.getBankCardTable(idcardnum);
        String strJson = JSON.toJSONString(bankCardTableList);
        HttpResult httpResult = new HttpResult();
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(JSONObject.parse(strJson));
        return httpResult;
    }

    public HttpResult getBankCreditSum(String idcardnum) {
        HttpResult httpResult = new HttpResult();
        httpResult.setStatus(0);
        httpResult.setMsg("success");
        httpResult.setData(BankCreditSum(idcardnum));
        return httpResult;
    }

    private int BankCreditSum(String idcardnum){
        int bankCreditSum = 0;
        List<BankCardTable> bankCardTableList = infoMapper.getBankCardTable(idcardnum);
        for (BankCardTable bankCardTable : bankCardTableList) {
            bankCreditSum += getBankCredit(bankCardTable.getBankcardnum());
        }
        return bankCreditSum;
    }
    private int getBankCredit(String bankcardnum) {
        return infoMapper.selectBankCredit(bankcardnum);
    }

}
